#!/usr/bin/env python
"""Usage: %prog INPUT_ASSETS.xml OUTPUT_DIR
Generates an appropriate class for each defined asset.
"""

import sys
import xml.etree.cElementTree as ET

def _find_assets(filename):
    """Finds info about assets defined in the filename.
    """
    assets = []
    tree = ET.parse(filename)
    for bitmap in tree.findall("//bitmap"):
        assets.append(dict(
            type="flash.display.BitmapData",
            id=bitmap.get("id"),
            super_new="super(0, 0);"
            ))

    return assets

CODE_TEMPLATE = """\
// This file is GENERATED by generate_class.py.
package %(package)s;

class %(name)s extends %(type)s {
    public function new() {
        %(super_new)s
    }
}
"""

def _generate_class(asset_info):
    """Takes {type,id} info and returns a class code.
    """
    ctx = dict(asset_info)
    ctx["package"], ctx["name"] = ctx["id"].rsplit(".", 1)
    return CODE_TEMPLATE % ctx


def main():
    args = sys.argv[1:]
    if len(args) != 2:
        print >>sys.stderr, __doc__
        sys.exit(1)

    input_filename = args[0]
    output_dir = args[1]

    assets = _find_assets(input_filename)
    for asset_info in assets:
        code = _generate_class(asset_info)
        path = "%s/%s.hx" % (output_dir, asset_info["id"].replace(".", "/"))

        print >>sys.stderr, "Producing %s" % path
        output = open(path, "w")
        output.write(code)
        output.close()


main()
